package com.sunny;

import redis.clients.jedis.Jedis;

import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Cart {

    private static final String DEFAULT_IP = "222.201.145.179";
    private static final int DEFAULT_PORT = 5056;

    private ExecutorService tp = Executors.newSingleThreadExecutor();

    private Jedis jedis;

    private String ip;
    private int port;

    public Cart() {
        jedis = new Jedis(DEFAULT_IP, DEFAULT_PORT);
    }

    public Cart(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void addToCart(String session, int item, int count){
        if(count <= 0){
            jedis.hdel("cart:" + session, String.valueOf(item));
        }else{
            jedis.hset("cart:"+session, String.valueOf(item), String.valueOf(count));
        }
    }

    public void startCleanThread(){
        tp.submit(()->{
            System.out.println("开始清理");
            boolean quit = false;
            long limit = 1000;
            while (!quit){
                long size = jedis.zcard("recent:");
                System.out.println("size="+size);
                if(size > limit){
                    try {
                        Thread.sleep(1000);
                        continue;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                long lastIndex = size - limit;
                Set<String> tokens = jedis.zrange("recent:",0, lastIndex-1);
                System.out.println("清理内存：" + tokens);
                tokens.forEach(token->{
                    jedis.hdel("token:",token);
                    jedis.zrem("recent:", token);
                    jedis.del("viewed:"+token);
                    jedis.hdel("cart:"+token);
                });
            }
        });
    }
}
